package com.jxt.mina.client;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.jxt.mina.tools.CodecFactory;


/**
 * mina转发消息类
 * @author scott
 *
 */
public class Client {

	private static Logger logger = Logger.getLogger(Client.class);
	private static final int PORT = 8888;
	/**
	 * 发送消息
	 * @param host
	 * @param message
	 * @param sendDate
	 * @param memberId
	 */
	public void send(String host,String message,String sendDate,String memberId,List listId) {
		IoConnector connector = new NioSocketConnector();
		connector.setConnectTimeout(30000);
		connector.getFilterChain().addLast(
				"codec",
				new ProtocolCodecFilter(new CodecFactory()));
		connector.setHandler(new ClientHandler());
		IoSession session = null;
		ConnectFuture connect = null;
		try {
			connect = connector.connect(new InetSocketAddress(
					host, PORT));
			connect.awaitUninterruptibly();
			session = connect.getSession();
			String flag = UUID.randomUUID().toString();
			session.setAttribute("userId", flag);
			JSONObject json = new JSONObject();
			json.accumulate("message", message);
			json.accumulate("date", sendDate);
			json.accumulate("memberId", memberId);
			json.accumulate("listId", listId);
			session.write(json);
		} catch (Exception e) {
			logger.error("客户端启动异常...",e);
		}finally{
//			session.getCloseFuture().awaitUninterruptibly();
			connector.dispose();
		}	
	}
}
